/**
 * Copyright &copy; 2012-2013 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.cn.ant.modules.sys.web;

import com.cn.ant.common.config.Global;
import com.cn.ant.common.utils.StringUtils;
import com.cn.ant.common.web.BaseController;
import com.cn.ant.modules.sys.entity.Area;
import com.cn.ant.modules.sys.service.AreaService;
import com.cn.ant.modules.sys.utils.UserUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 区域Controller
 * 
 * @author ThinkGem
 * @version 2013-5-15
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/area")
public class AreaController extends BaseController {

    @Autowired
    private AreaService areaService;

    @ModelAttribute("area")
    public Area get(@RequestParam(required = false) String id) {
        if (StringUtils.isNotBlank(id)) {
            return areaService.get(id);
        } else {
            return new Area();
        }
    }

    @RequiresPermissions("sys:area:view")
    @RequestMapping(value = { "list", "" })
    public String list(Area area, Model model, HttpServletRequest request) {
        String menuId = request.getParameter("menuId");
        area.setId("1");
        model.addAttribute("area", area);
        List<Area> list = Lists.newArrayList();
        List<Area> sourcelist = areaService.findAll();
        Area.sortList(list, sourcelist, area.getId());
        model.addAttribute("list", list);
        model.addAttribute("menuId", menuId);
        return "modules/sys/areaList";
    }

    @RequiresPermissions("sys:area:view")
    @RequestMapping(value = "form")
    public String form(Area area, Model model, HttpServletRequest request) {
        String menuId = request.getParameter("menuId");
        if (area.getParent() == null || area.getParent().getId() == null) {
            area.setParent(UserUtils.getUser().getOffice().getArea());
        }
        // area.setParent(areaService.get(area.getParent().getId()));
        model.addAttribute("menuId", menuId);
        model.addAttribute("area", area);
        return "modules/sys/areaForm";
    }

    @RequiresPermissions("sys:area:edit")
    @RequestMapping(value = "save")
    public String save(Area area, Model model, RedirectAttributes redirectAttributes, HttpServletRequest request) {
        if (Global.isDemoMode()) {
            addMessage(redirectAttributes, "演示模式，不允许操作！");
            return "redirect:" + Global.getAdminPath() + "/sys/area";
        }
        if (!beanValidator(model, area)) {
            return form(area, model, request);
        }
        areaService.save(area);
        addMessage(redirectAttributes, "保存区域'" + area.getName() + "'成功");
        return "redirect:" + Global.getAdminPath() + "/sys/area/";
    }

    @RequiresPermissions("sys:area:edit")
    @RequestMapping(value = "delete")
    public String delete(String id, RedirectAttributes redirectAttributes) {
        if (Global.isDemoMode()) {
            addMessage(redirectAttributes, "演示模式，不允许操作！");
            return "redirect:" + Global.getAdminPath() + "/sys/area";
        }
        if (Area.isAdmin(id)) {
            addMessage(redirectAttributes, "删除区域失败, 不允许删除顶级区域或编号为空");
        } else {
            areaService.delete(id);
            addMessage(redirectAttributes, "删除区域成功");
        }
        return "redirect:" + Global.getAdminPath() + "/sys/area/";
    }

    @RequiresUser
    @ResponseBody
    @RequestMapping(value = "treeData")
    public List<Map<String, Object>> treeData(@RequestParam(required = false) String extId,
            @RequestParam(required = false) String parentId,HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("application/json; charset=UTF-8");
        List<Map<String, Object>> mapList = Lists.newArrayList();
        // User user = UserUtils.getUser();
        Map<String, String> params = new HashMap<>();
        String type = request.getParameter("type");
        if("undefined".equals(parentId)){
            parentId = "";
        }
        params.put("extId", extId);
        params.put("parentId", parentId);
        params.put("type", type);
        List<Area> list = areaService.query(params);
        for (int i = 0; i < list.size(); i++) {
            Area e = list.get(i);
            if (extId == null || (extId != null && !extId.equals(e.getId())
                    && e.getParentIds().indexOf("," + extId + ",") == -1)) {
                Map<String, Object> map = Maps.newHashMap();
                map.put("id", e.getId());
                // map.put("pId",
                // !user.isAdmin()&&e.getId().equals(user.getArea().getId())?0:e.getParent()!=null?e.getParent().getId():0);
                map.put("pId", e.getParent() != null ? e.getParent().getId() : 0);
                map.put("name", e.getName());
                mapList.add(map);
            }
        }
        return mapList;
    }

    /**
     * 根据父code查询子区域
     * @param parentCode
     * @param request
     * @return
     */
    @RequestMapping(value = "getByParentCode")
    @ResponseBody
    public List<Map<String, String>> getByParentCode(@RequestParam(required = true) String parentCode, HttpServletRequest request) {
        List<Map<String, String>> result = new ArrayList<Map<String, String>>();
        Map<String, String> params = new HashMap<>();
        params.put("parentCode", parentCode);
        List<Area> areaList = areaService.query(params);
        for (Area area : areaList) {
            Map<String, String> temp = new HashMap<>();
            temp.put("name", area.getName());
            temp.put("id", area.getId());
            temp.put("code", area.getCode());
            result.add(temp);
        }
        return result;
    }
}
